import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:frontend/states/NetState.dart';
import 'package:image_picker/image_picker.dart';
import 'package:frontend/reqs/requests.dart';
import 'package:frontend/states/userState.dart';
import 'package:frontend/utils.dart';
import 'package:provider/provider.dart';

import '../models/address.dart';

class AddressEditPage extends StatefulWidget {
  const AddressEditPage({super.key, this.address});

  final Address? address;

  @override
  _AddressEditPageState createState() => _AddressEditPageState();
}

class _AddressEditPageState extends State<AddressEditPage> {
  TextEditingController _addressController = TextEditingController();
  TextEditingController _contactController = TextEditingController();
  TextEditingController _phoneNumberController = TextEditingController();
  GlobalKey _formKey = GlobalKey<FormState>();
  static List<String> addressTags = [
    '其他',
    '家',
    '公司',
    '学校',
  ];
  String addressTag = '无';

  @override
  void initState() {
    super.initState();
    if (widget.address != null) {
      addressTag = widget.address!.tag;
      _addressController.text = widget.address!.address;
      _contactController.text = widget.address!.contact;
      _phoneNumberController.text = widget.address!.phone_number;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("编辑地址"),
      ),
      body: Container(
        padding: const EdgeInsets.all(24),
        child: ListView(
          children: [
            Row(
              children: [
                for (var tag in addressTags)
                  ChoiceChip(
                    label: Text(tag),
                    selected: tag == addressTag,
                    onSelected: (bool selected) {
                      setState(() {
                        addressTag = selected ? tag : '无';
                      });
                    },
                  ),
              ],
            ),
            Form(
              key: _formKey, //设置globalKey，用于后面获取FormState
              autovalidateMode: AutovalidateMode.onUserInteraction,
              child: Column(
                children: <Widget>[
                  TextFormField(
                    autofocus: true,
                    controller: _addressController,
                    decoration: InputDecoration(
                      labelText: "详细地址",
                      hintText: "在何处收货",
                      icon: Icon(Icons.where_to_vote_outlined),
                    ),
                    validator: (v) {
                      return v!.trim().isNotEmpty ? null : "地址不能为空";
                    },
                  ),
                  TextFormField(
                    controller: _contactController,
                    decoration: InputDecoration(
                      labelText: "联系人名字",
                      hintText: "收货联系人",
                      icon: Icon(Icons.people),
                    ),
                    validator: (v) {
                      return v!.trim().isNotEmpty ? null : "联系人名字不能为空";
                    },
                  ),
                  TextFormField(
                    controller: _phoneNumberController,
                    decoration: InputDecoration(
                      labelText: "电话号码",
                      hintText: "联系人电话号码",
                      icon: Icon(Icons.phone),
                    ),
                    validator: (v) {
                      return v!.trim().isNotEmpty ? null : "联系人电话不能为空";
                    },
                  ),
                  Padding(
                    padding: const EdgeInsets.only(top: 28.0),
                    child: Row(
                      children: <Widget>[
                        ElevatedButton(
                            onPressed: () {
                              if ((_formKey.currentState as FormState)
                                  .validate()) {
                                if (widget.address != null) {
                                  updateAddress(
                                      widget.address!.address_id,
                                      Address(
                                          widget.address!.address_id,
                                          addressTag,
                                          _addressController.text,
                                          _contactController.text,
                                          _phoneNumberController.text));
                                } else {
                                  addAddress(Address(
                                      -1,
                                      addressTag,
                                      _addressController.text,
                                      _contactController.text,
                                      _phoneNumberController.text));
                                }
                                ScaffoldMessenger.of(context).showSnackBar(
                                  const SnackBar(
                                    content: Text('地址已编辑！'),
                                  ),
                                );
                                Provider.of<NetState>(context, listen: false)
                                    .somethingChangedInBackend();
                                Navigator.pop(context);
                              }
                            },
                            child: Text("确认")),
                      ],
                    ),
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}
